package com.wz.dhs.config;

import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;

/**
 * @param
 * @author xyb
 * @description: Mybatis日志打印 【使用Mybatis自带拦截器拦截StatementHandler里的update和query方法。【insert以及delete均是最终调用update】】
 * @date 2021/7/14
 * @return
 */
@ConditionalOnProperty(prefix = "log", name = "mybatis", havingValue = "enable")
@ConditionalOnClass(name = {"org.apache.ibatis.session.defaults.DefaultSqlSessionFactory"})
@Component
@Accessors(chain = true)
@Intercepts(value = {
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),//需要代理的对象和方法
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})//需要代理的对象和方法
})
@Slf4j
public class MybatisLogConfiguration implements Interceptor {

    //存放执行sql的随机ID
    public ThreadLocal execute = new ThreadLocal();

    //忽略的方法
    public static final String[] ignoreMethod = {"prepare", "parameterize"};

    public static final String STATEMENT_FIELD_NAME = "delegate";

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        Object returnValue = null;
        try {
            if (args != null && args.length > 0) {
                MappedStatement mappedStatement = (MappedStatement)args[0];
                if(args.length > 1){
                    String sqlId = mappedStatement.getId();//获得mybatis的*mapper.xml文件中映射的方法，如：com.best.dao.UserMapper.selectById

                    //将参数和映射文件组合在一起得到BoundSql对象
                    BoundSql boundSql = mappedStatement.getBoundSql(args[1]);
                    //获取配置信息
                    Configuration configuration = mappedStatement.getConfiguration();
                    //通过配置信息和BoundSql对象来生成带值得sql语句
                    String sql = geneSql(configuration, boundSql);
                    //打印sql语句
                    log.info("sql执行位置:{}",sqlId);
                    log.info("sql语句:{}",sql);
                }
            }
        }
        catch (Exception e){
            log.info("拦截sql出现异常:{}",e);
        }
        finally {
            returnValue = invocation.proceed();
            log.info("执行结果===》:{}",returnValue == null ? "执行返回值为NULL" : returnValue.toString());
            return returnValue;
        }
    }


    /**
     * 这里可以对目标对象进行代理。可以选择在这里对Executor.query进行增强。也可以使用上面拦截器进行拦截处理
     *
     * @param target
     * @return
     */
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }


    /**
     * 生成对应的带有值得sql语句
     * @param configuration
     * @param boundSql
     * @return
     */
    public static String geneSql(Configuration configuration, BoundSql boundSql) {

        Object parameterObject = boundSql.getParameterObject();//获得参数对象，如{id:1,name:"user1",param1:1,param2:"user1"}
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();//获得映射的对象参数
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");//获得带问号的sql语句
        if (parameterMappings.size() > 0 && parameterObject != null) {//如果参数个数大于0且参数对象不为空，说明该sql语句是带有条件的
            MetaObject metaObject = configuration.newMetaObject(parameterObject);//将映射文件的参数和对应的值返回，比如：id，name以及对应的值。
            for (ParameterMapping parameterMapping : parameterMappings) {//遍历参数，如:id,name等
                String propertyName = parameterMapping.getProperty();//获得属性名，如id,name等字符串
                if (metaObject.hasGetter(propertyName)) {//检查该属性是否在metaObject中
                    Object obj = metaObject.getValue(propertyName);//如果在metaObject中，那么直接获取对应的值
                    sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));//然后将问号?替换成对应的值。
                } else if (boundSql.hasAdditionalParameter(propertyName)) {
                    Object obj = boundSql.getAdditionalParameter(propertyName);
                    sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
                }
            }
        }
        return sql;//最后将sql语句返回
    }

    /**
     * 如果是字符串对象则加上单引号返回，如果是其他则直接转换成字符串返回。
     * @param obj
     * @return
     */
    private static String getParameterValue(Object obj) {
        String value;
        if (obj instanceof String) {
            value = "'" + obj.toString() + "'";
        }
        else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "";
            }

        }
        return value;
    }

}
